package com.util.openBdf;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.knaw.dans.common.dbflib.CorruptedTableException;
import nl.knaw.dans.common.dbflib.DbfLibException;
import nl.knaw.dans.common.dbflib.Field;
import nl.knaw.dans.common.dbflib.IfNonExistent;
import nl.knaw.dans.common.dbflib.Record;
import nl.knaw.dans.common.dbflib.Table;
import nl.knaw.dans.common.dbflib.ValueTooLargeException;

/*
 * Usage: java -cp dans-dbf-lib-version.jar:dump-table.jar nl.knaw.dans.common.example.DumpTable <table file>
 */
public class DpfHandler
{
    String fname;
    Table table;
    List<Field> fields;
    Iterator<Record> recordIterator;
    public DpfHandler(String fname) {
        try {
            this.fname = fname;
            table = new Table(new File(fname));
            table.open(IfNonExistent.ERROR);
            fields = table.getFields();
            recordIterator = table.recordIterator();
        } catch (IOException ex) {
            Logger.getLogger(DpfHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CorruptedTableException ex) {
            Logger.getLogger(DpfHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public String[] getFieldsName(){
        String[] names = new String[1+fields.size()];
        int i = 0;
        for(Field field: fields)
        {
            names[i] = field.getName();
            i++;
        }
        return names;
    }

    public List<Object> readNext() {
        try
        {
            int count = 0;
            List<Object> result = new ArrayList<Object>();
            if(recordIterator.hasNext())
            {
                final Record record = recordIterator.next();
                for(final Field field: fields)
                {
                    try
                    {
                        result.add(new String(record.getRawValue(field)).trim());
                    }
                    catch(ValueTooLargeException vtle)
                    {
                        return null;
                    }
                }
                return result;
            }
            else{
                return null;
            }
        }
        catch(DbfLibException dbflibException)
        {
            System.out.println("Problem getting raw value");
            dbflibException.printStackTrace();
            return null;
        }
     }

    
    public static void main(String[] args)
    {
        String fileName = "t.dbf";
        final Table table = new Table(new File(fileName));

        try
        {
            table.open(IfNonExistent.ERROR);

            final Format dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            System.out.println("TABLE PROPERTIES");
            System.out.println("Name          : " + table.getName());
            System.out.println("Last Modified : " + dateFormat.format(table.getLastModifiedDate()));
            System.out.println("--------------");
            System.out.println();
            System.out.println("FIELDS (COLUMNS)");

            final List<Field> fields = table.getFields();

            for(final Field field: fields)
            {
                System.out.println("  Name       : " + field.getName());
                System.out.println("  Type       : " + field.getType());
                System.out.println("  Length     : " + field.getLength());
                System.out.println("  Dec. Count : " + field.getDecimalCount());
                System.out.println();
            }

            System.out.println("--------------");
            System.out.println();
            System.out.println("RECORDS");

            final Iterator<Record> recordIterator = table.recordIterator();
            int count = 0;

            while(recordIterator.hasNext())
            {
                final Record record = recordIterator.next();
                System.out.println(count++);

                for(final Field field: fields)
                {
                    try
                    {
                        byte[] rawValue = record.getRawValue(field);
                        System.out.println(field.getName() + " : " + (rawValue == null ? "<NULL>" : new String(rawValue)));
                    }
                    catch(ValueTooLargeException vtle)
                    {
                        // Cannot happen :)
                    }
                }

                System.out.println();
            }

            System.out.println("--------------");
        }
        catch(IOException ioe)
        {
            System.out.println("Trouble reading table or table not found");
            ioe.printStackTrace();
        }
        catch(DbfLibException dbflibException)
        {
            System.out.println("Problem getting raw value");
            dbflibException.printStackTrace();
        }
        finally
        {
            try
            {
                table.close();
            } catch (IOException ex)
            {
                System.out.println("Unable to close the table");
            }
        }
    }
}